package com.hector.meinewerk.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.widget.ImageView;

import com.hector.meinewerk.client.R;
import com.hector.meinewerk.common.ServerPath;

public class ImageLoader {

	private static final int MAX_IMAGES_CACHED = 30;
	// the simplest in-memory cache implementation. This should be replaced with
	// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
	private static HashMap<String, Bitmap> mCacheBitmap;
	private static ArrayList<String> mImagesUrl = new ArrayList<String>();
	private static File cacheDir;
	static PhotosLoader photoLoaderThread;
	static PhotosQueue photosQueue;

	public ImageLoader(Context context) {

		if (mCacheBitmap == null) {
			mCacheBitmap = new HashMap<String, Bitmap>();
		}
		if (photosQueue == null) {
			photosQueue = new PhotosQueue();
		}

		if (photoLoaderThread == null) {
			photoLoaderThread = new PhotosLoader();
			photoLoaderThread.start();
		}

		// Make the background thead low priority. This way it will not affect
		// the UI performance
		photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);

		// Find the dir to save cached images
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					"LazyList");
		else
			cacheDir = context.getCacheDir();
		if (!cacheDir.exists())
			cacheDir.mkdirs();
	}

	final int stub_id = R.drawable.no_image;

	public void DisplayImage(String url, ImageView imageView) {
		if (TextUtils.isEmpty(url) || (imageView == null)) {
			return;
		}
		
		if(url.startsWith("http://") || url.startsWith("https://")){
			
		}else{
			url = ServerPath.URL_IMAGE + url;
		}
		
		imageView.setTag(url);

		if (mCacheBitmap.containsKey(url)) {
			if (mCacheBitmap.get(url) != null) {
				imageView.setImageBitmap(mCacheBitmap.get(url));
			} else {
				queuePhoto(url, imageView);
				imageView.setImageResource(stub_id);
			}
		} else {
			queuePhoto(url, imageView);
			imageView.setImageResource(stub_id);
		}
	}

	public Bitmap getBitmapCache(String url) {
		if (mCacheBitmap.containsKey(url)) {
			return mCacheBitmap.get(url);
		}

		return null;
	}

	private void queuePhoto(String url, ImageView imageView) {
		// This ImageView may be used for other images before. So there may be
		// some old tasks in the queue. We need to discard them.

		synchronized (photosQueue.photosToLoad) {
			// photosQueue.Clean(imageView);
			PhotoToLoad p = new PhotoToLoad(url, imageView);
			photosQueue.photosToLoad.add(p);
			photosQueue.photosToLoad.notifyAll();
		}

		// start thread if it's not started yet
		// if (photoLoaderThread.getState() == Thread.State.NEW)
		// photoLoaderThread.start();
	}

	public Bitmap getBitmapBackground(String url) {
		if (url == null) {
			return null;
		}

		Bitmap bmp = null;
		if (mCacheBitmap.containsKey(url)) {
			if (mCacheBitmap.get(url) != null) {
				bmp = mCacheBitmap.get(url);
				if (bmp != null) {
					return bmp;
				}

			} else {
				mCacheBitmap.remove(url);
			}
		}

		if (bmp == null) {
			bmp = getBitmap(url);
		}
		if (bmp != null) {

			mCacheBitmap.put(url, bmp);

		}
		return bmp;
	}
	
	public String saveFileBitmap(String fileName, Bitmap bm) {
		File filePath = new File(cacheDir, fileName);
		String filename = String.valueOf(filePath.getAbsolutePath().hashCode());
		File file = new File(cacheDir, filename);
		OutputStream outStream = null;
		try {
			outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();
			mCacheBitmap.put(filePath.getAbsolutePath(), null);
			return filePath.getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	public void updateKey(String newKey, String oldKey){
		if (mCacheBitmap.containsKey(oldKey)) {
			mCacheBitmap.put(newKey, mCacheBitmap.get(oldKey));
			mCacheBitmap.remove(oldKey);
		}
	}

	public Bitmap getBitmap(String url) {
		// I identify images by hashcode. Not a perfect solution, good for the
		// demo.
		String filename = String.valueOf(url.hashCode());
		File f = new File(cacheDir, filename);
		// from SD cache
		/* Bitmap b = decodeFile(f); */
		Bitmap b = getLargeBitmap(f.getAbsolutePath());
		if (b != null)
			return b;
		// from web

		try {
			if (f.exists()) {
				f.delete();
			}
			Bitmap bitmap = null;
			InputStream is = new URL(url).openStream();
			OutputStream os = new FileOutputStream(f);
			Utils.CopyStream(is, os);
			os.close();
			// bitmap = decodeFile(f);
			bitmap = getLargeBitmap(f.getAbsolutePath());
			return bitmap;
		} catch (Exception ex) {
			// ex.printStackTrace();
			if (f.exists()) {
				f.delete();
			}
			// ErrorStatus.setErrorNoNetWorkConnection();

		}
		return null;
	}

	public static Bitmap getLargeBitmap(final String filePath) {
		final BitmapFactory.Options bfOptions = new BitmapFactory.Options();
		bfOptions.inDither = false; // Disable Dithering mode
		bfOptions.inPurgeable = true; // Tell to gc that whether it needs free
		// memory, the Bitmap can be cleared
		bfOptions.inInputShareable = true; // Which kind of reference will be
		// used to recover the Bitmap data
		// after being clear, when it will be
		// used in the future
		bfOptions.inTempStorage = new byte[32 * 1024];

		final File file = new File(filePath);
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(file);
		} catch (final FileNotFoundException e) {
			// e.printStackTrace();
			return null;
		}
		try {
			if (fs != null) {
				final Bitmap bm = BitmapFactory.decodeFileDescriptor(
						fs.getFD(), null, bfOptions);
				if (bm != null) {
				}
				return bm;
			}
		} catch (final Exception e) {
			e.printStackTrace();
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (final IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	// decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale++;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	// Task for the queue
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	public static void stopThread() {
		try {
			photoLoaderThread.interrupt();
			clearCache();
			synchronized (photosQueue.photosToLoad) {
				photosQueue.photosToLoad.clear();
			}
			photoLoaderThread = null;
			// photosQueue = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// stores list of photos to download
	class PhotosQueue {
		// private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();

		Queue<PhotoToLoad> photosToLoad = new LinkedList<PhotoToLoad>();

		// removes all instances of this ImageView
		public void Clean(ImageView image) {
			// Iterator it = photosToLoad.iterator();
			// while (it.hasNext()) {
			// PhotoToLoad iteratorValue = (PhotoToLoad) it.next();
			//
			// if (iteratorValue.imageView == image)
			// photosToLoad.remove(iteratorValue);
			// }
		}
	}

	class PhotosLoader extends Thread {
		public void run() {
			try {
				while (true) {

					// thread waits until there are any images to load in the
					// queue
					if (photosQueue.photosToLoad.size() == 0)
						synchronized (photosQueue.photosToLoad) {
							photosQueue.photosToLoad.wait();
						}
					if (photosQueue.photosToLoad.size() != 0) {
						PhotoToLoad photoToLoad;
						synchronized (photosQueue.photosToLoad) {
							photoToLoad = photosQueue.photosToLoad.poll();
						}
						Bitmap bmp = getBitmap(photoToLoad.url);
						if (bmp != null) {
							String removedUrl="";
							if(mImagesUrl.size() == MAX_IMAGES_CACHED){
								removedUrl = mImagesUrl.remove(0);
							}
							
							mImagesUrl.add(photoToLoad.url);
							if(!TextUtils.isEmpty(removedUrl)){
								mCacheBitmap.remove(removedUrl);
							}
							mCacheBitmap.put(photoToLoad.url, bmp);
							if (((String) photoToLoad.imageView.getTag())
									.equals(photoToLoad.url)) {

								// Thien resize bitmap
								// resizeBitmap(photoToLoad.imageView, bmp); -
								// Hung
								// removed it for now...9/3/2012

								try {
									BitmapDisplayer bd = new BitmapDisplayer(
											bmp, photoToLoad.imageView);
									Activity a = (Activity) photoToLoad.imageView
											.getContext();
									a.runOnUiThread(bd);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						} else {
							synchronized (photosQueue.photosToLoad) {
								if (photoToLoad != null)
									photosQueue.photosToLoad.add(photoToLoad);
							}
						}

					}
					if (Thread.interrupted())
						break;
				}
			} catch (InterruptedException e) {
				// allow thread to exit
			}
		}
	}

	// Used to display bitmap in the UI thread
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		ImageView imageView;

		public BitmapDisplayer(Bitmap b, ImageView i) {
			bitmap = b;
			imageView = i;
		}

		public void run() {
			if (bitmap != null) {
				imageView.setImageBitmap(bitmap);
			} else {
				imageView.setImageResource(stub_id);
			}
		}
	}

	public static void clearCache() {
		// clear memory cache
		mCacheBitmap.clear();

		// clear SD cache
		File[] files = cacheDir.listFiles();
		for (File f : files)
			f.delete();
	}
}
